package com.meixiang.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.activity.calendar.MemorandumActivity;
import com.meixiang.activity.homes.service.ServiceDetailActivity;
import com.meixiang.adapter.calendar.CalendarStyleAdapter;
import com.meixiang.dialog.AlertDialogFragment;
import com.meixiang.entity.calaendar.CalendarResult;
import com.meixiang.entity.calaendar.ScheduleListBean;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseFragment;
import com.meixiang.main.MXApplication;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.view.Calendar.MonthDateView;
import com.meixiang.view.swipetoloadlayout.base.OnLoadMoreListener;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 日历
 * 作者：黑哥 on 2016/3/29 11:39
 */
public class CalendarFragment extends BaseFragment implements View.OnClickListener, OnRefreshListener, OnLoadMoreListener {
    @Bind(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @Bind(R.id.tv_menmo)
    TextView mTvMenmo;
    @Bind(R.id.swipe_target)
    ScrollView mSwipeTarget;
    @Bind(R.id.refresh)
    SwipeToLoadLayout mRefresh;
    private View view;
    private FragmentActivity mActivity;
    private MonthDateView md_monthdata;
    private TextView tv_date, tv_week;
    private ImageView iv_left, iv_right;
    private List<CalendarResult> mCalendarResult;
    private CalendarStyleAdapter mAdapter;


    private String year, month, day, dYear, dMonth;
    private int current_month, getDataCurrentMonth;
    private List<ScheduleListBean> mScheduleLists;

    private boolean isDay = false;

    private String scheduleId;
    private List<ScheduleListBean> mScheduleList = new ArrayList<>();
    private boolean isSelect = false;

    public CalendarFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_calendar, container, false);
        super.onCreateView(inflater, container, savedInstanceState);
        mActivity = getActivity();
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initTitle() {

    }

    @Override
    protected void initView() {
        md_monthdata = (MonthDateView) view.findViewById(R.id.monthDateView);
        tv_date = (TextView) view.findViewById(R.id.date_text);
        md_monthdata.setTextView(tv_date, tv_week);
        iv_left = (ImageView) view.findViewById(R.id.iv_left);
        iv_right = (ImageView) view.findViewById(R.id.iv_right);
        md_monthdata.setTodayToView();


        year = md_monthdata.getmSelYear() + "";
        current_month = md_monthdata.getmSelMonth() + 1;
        month = current_month + "";
        day = md_monthdata.getmSelDay() + "";

        mRefresh.setOnRefreshListener(this);
        mRefresh.setOnLoadMoreListener(this);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mAdapter = new CalendarStyleAdapter(getActivity());
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new CalendarStyleAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, boolean isDelete) {
                scheduleId = +mAdapter.mDayList.get(position).getScheduleId() + "";
                if (isDelete == true) {
                    //执行删除
                    new AlertDialogFragment.Builder()
                            .setContentText("确认删除备忘？")
                            .setLeftBtnText("确认").setLeftClickCallBack(new AlertDialogFragment.LeftClickCallBack() {
                        @Override
                        public void dialogLeftBtnClick() {
                            doDelet(scheduleId);

                        }
                    }).setRightBtnText("取消")
                            .build()
                            .show(getChildFragmentManager(), AlertDialogFragment.TAG);


                } else {
                    //查看跟多


                    checkMore(scheduleId);
                }
            }
        });


        mRefresh.setLoadMoreEnabled(false);

        iv_left.setOnClickListener(this);

        iv_right.setOnClickListener(this);
        mTvMenmo.setOnClickListener(this);
    }

    @Override
    protected void setData() {


        isDay = true;
        if (MXApplication.mApp.hasLogin()) {
            doSetData(year, month);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (MXApplication.mApp.hasLogin()) {
            doSetData(year, month);
            if (isSelect == true) {
                int mSelectMonth = md_monthdata.getmSelMonth() + 1;
                if (dYear.equals(md_monthdata.getmSelYear() + "") && dMonth.equals(mSelectMonth + "")) {
                    for (int i = 0; i < mCalendarResult.size(); i++) {
                        mScheduleList = mCalendarResult.get(i).getScheduleList();
                        if (md_monthdata.getmSelDay() == Integer.valueOf(Tool.toDay(mCalendarResult.get(i).getRemindTime()))) {
                            mAdapter.clear();
                            mAdapter.addAll(mScheduleList);
                        }
                    }
                }
            }
        }
    }

    private void doSetData(String year, String month) {

        HttpParams params = new HttpParams();
        params.put("year", year);
        params.put("month", month);
        HttpUtils.post(Config.CALENDAR_FOR_DATA, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                mRefresh.setRefreshing(false);
                Log.e("response", result.toString() + "code:" + code);
                mCalendarResult = AbJsonUtil.fromJson(result.optString("List").toString(), new TypeToken<List<CalendarResult>>() {
                });
                dYear = result.optInt("year") + "";
                dMonth = result.optInt("month") + "";
                getDataCurrentMonth = result.optInt("month");

                md_monthdata.setCalendarList(mCalendarResult, dYear, dMonth);

                md_monthdata.onGetDayLisyListener(new MonthDateView.getDayLisy() {
                    @Override
                    public void getDayData(List<ScheduleListBean> mDayList) {
                        if (mDayList != null) {
                            mAdapter.clear();
                        }
                        mAdapter.addAll(mDayList);
                    }
                });
                if (isSelect == false) {
                    AddAdapterData();

                }

            }

            @Override
            public void onError(String code, String message) {
                Toast.makeText(mActivity, message, Toast.LENGTH_LONG).show();
                mRefresh.setRefreshing(false);
            }
        });

    }


    private void AddAdapterData() {
        md_monthdata.setDateClick(new MonthDateView.DateClick() {
            @Override
            public void onClickOnDate() {

                //得到当前下标点的 数据

                int mSelectMonth = md_monthdata.getmSelMonth() + 1;
                if (dYear.equals(md_monthdata.getmSelYear() + "") && dMonth.equals(mSelectMonth + "")) {
                    for (int i = 0; i < mCalendarResult.size(); i++) {
                        mScheduleList = mCalendarResult.get(i).getScheduleList();
                        Log.e("TAG", "输出数据list" + mScheduleList.size());
                        if (md_monthdata.getmSelDay() == Integer.valueOf(Tool.toDay(mCalendarResult.get(i).getRemindTime()))) {
                            mAdapter.clear();
                            mAdapter.addAll(mScheduleList);
                        }
                    }
                }
                isSelect = true;
            }

        });
    }

    //删除
    private void doDelet(String scheduleId) {
        HttpParams params = new HttpParams();
        params.put("scheduleId", scheduleId);
        HttpUtils.post(Config.CALENDAR_BACKUP_DELETE, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                onRefresh();
                Tool.showTextToast(mActivity, message);
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(mActivity, message);
            }
        });
    }

    //查看更多
    private void checkMore(final String scheduleId) {
        HttpParams params = new HttpParams();
        params.put("scheduleId", scheduleId);
        HttpUtils.post(Config.CALENDAR_BACKUP_DETAIL, params, new HttpCallBack(mActivity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Tool.showTextToast(mActivity, message);
                onRefresh();
                Intent intent = new Intent(mActivity, ServiceDetailActivity.class);
                intent.putExtra("goodsId", scheduleId);
                startActivity(intent);

            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(mActivity, message);
            }
        });


    }

    public void onClick(View v) {
        if (v.equals(iv_left)) {

            year = md_monthdata.getmSelYear() + "";
            day = md_monthdata.getmSelDay() + "";
            current_month = md_monthdata.getmSelMonth();
            month = current_month-- + "";
//            if(Integer.valueOf(dMonth)>Integer.valueOf(month)){
//                iv_left.setImageResource(R.mipmap.month_3);
//                iv_left.setEnabled(false);
//                return;
//            }
            md_monthdata.onLeftClick();
            Log.e("TAG", "输出当前选中的月份left=" + month);
            doSetData(year, month);

        }
        if (v.equals(iv_right)) {
            md_monthdata.onRightClick();
            year = md_monthdata.getmSelYear() + "";
            day = md_monthdata.getmSelDay() + "";
            current_month = md_monthdata.getmSelMonth() + 1;
            month = current_month++ + "";
            doSetData(year, month);
        }
        if (v.equals(mTvMenmo)) {
            day = md_monthdata.getmSelDay() + "";
            Intent intent = new Intent(getActivity(), MemorandumActivity.class);
            intent.putExtra("year", year);
            intent.putExtra("month", month);
            intent.putExtra("day", day);
            startActivity(intent);

        }


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onRefresh() {
        doSetData(year, month);
    }

    @Override
    public void onLoadMore() {
        mRefresh.setLoadingMore(false);
    }


}
